import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { getWeather, getCityIp } from '@/api/weather'

export const useWeatherStore = defineStore('weather', () => {
  // 添加操作cityList的方法
  const addCity = (city) => {
    if (!cityList.value.some((c) => c.adcode === city.adcode)) {
      cityList.value.push(city)
    }
  }

  const deleteCity = (adcode) => {
    cityList.value = cityList.value.filter((c) => c.adcode !== adcode)
  }
  const cityList = ref(JSON.parse(localStorage.getItem('cityList')) || [])
  watch(
    cityList,
    (newList) => {
      localStorage.setItem('cityList', JSON.stringify(newList))
    },
    { deep: true }
  )

  const cityName = ref('') // 城市名称
  const cityAdcode = ref('') // 城市编码
  const nowWeather = ref({}) // 实时天气
  const option = ref({}) // 图表信息
  const futureWeathers = ref([]) // 未来天气
  // 获取当前城市信息和实时天气
  const getCurrentCityWeather = async () => {
    try {
      // 获取当前城市信息
      const cityData = await getCityIp()
      cityName.value = cityData.city
      cityAdcode.value = cityData.adcode
      // 获取实时天气,注意这里的两个参数adcode和type
      const weatherData = await getWeather(cityAdcode.value, 'base')
      nowWeather.value = weatherData.lives[0]
      return { city: cityName.value, weather: nowWeather.value }
    } catch (error) {
      console.error('失败:', error)
      return { city: '', weather: {} }
    }
  }
  // 图表信息
  const renderOption = () => {
    option.value = {
      xAxis: {
        type: 'category',
        show: false,
        boundaryGap: false,
      },
      yAxis: {
        type: 'value',
        show: false,
      },
      grid: {
        top: 50,
        left: 80,
        right: 80,
        bottom: 50,
      },
      series: [
        {
          name: 'Highest',
          type: 'line',
          data: futureWeathers.value.map((item) => item.daytemp),
          smooth: true,
          label: {
            show: true,
            position: 'top',
            color: '#fff',
            formatter: '白{c}°C',
          },
        },
        {
          name: 'Lowest',
          type: 'line',
          data: futureWeathers.value.map((item) => item.nighttemp),
          smooth: true,
          label: {
            show: true,
            position: 'bottom',
            color: '#fff',
            formatter: '晚{c}°C',
          },
        },
      ],
    }
  }

  // 获取天气数据
  const getWeatherData = async (key) => {
    try {
      // 如果没有key，先获取当前城市
      if (!key) {
        if (!cityAdcode.value) {
          const res = await getCityIp()
          cityAdcode.value = res.adcode
          cityName.value = res.city
        }
        key = cityAdcode.value
      }
      // 获取所有天气数据
      const res = await getWeather(key, 'all')
      futureWeathers.value = res.forecasts[0].casts
      // 渲染图表
      renderOption()
      return futureWeathers.value
    } catch (error) {
      console.error('获取失败:', error)
      return []
    }
  }

  // 获取星期几
  const getWeekDay = (item) => {
    const index = futureWeathers.value.findIndex((weather) => weather.date === item.date)
    if (index === 0) {
      return '今天'
    } else if (index === 1) {
      return '明天'
    } else {
      const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      const date = new Date(item.date)
      return weekDays[date.getDay()]
    }
  }
  const weatherInfos = computed(() => {
    return futureWeathers.value.map((item) => {
      return {
        week: getWeekDay(item),
        date: item.date.slice(5),
        dayweather: item.dayweather,
        daypower: item.daypower,
      }
    })
  })
  return {
    futureWeathers,
    nowWeather,
    cityName,
    cityAdcode,
    option,
    weatherInfos,

    cityList,
    addCity,
    deleteCity,

    renderOption,
    getWeatherData,
    getCurrentCityWeather,
  }
})
